<script setup lang="ts">
import {dailyMenuTypeOpts, statusOpt1} from "@/utils/status";
import {
  addDailyMenuProducts,
  copyDailyMenu,
  createDailyMenu,
  DailyMenuForm,
  DailyMenuProduct,
  DailyMenuProductCategory,
  DailyMenuQuery,
  deleteDailyMenu,
  deleteProduct,
  getDailyMenuDetail,
  getDailyMenuList,
  getMenuProducts,
  getMenuProductsOptions,
  sortDailyMenu,
  updateDailyMenu,
} from "@/api/shop/dailyMenu";
import {dailyMenuFields} from "@/utils/field";
import {getSupplierOptions} from "@/api/supplier";
import defaultSettings from "@/settings";
import {useUserStore} from "@/store";

defineOptions({
  name: "DailyMenu",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const objFormRef = ref(ElForm);
const current_role = localStorage.getItem("role_name");
const loading = ref(false);
const total = ref(0);
const lastPage = ref(0);
const useStore = useUserStore();

const modelFields = ref<DailyMenuForm>();
modelFields.value = dailyMenuFields(0);
const step = ref(0);
const statusOptions = statusOpt1();
const typeOptions = dailyMenuTypeOpts();

const queryParams = reactive<DailyMenuQuery>({
  pageNum: 1,
  pageSize: 10,
});

const lists = ref<DailyMenuQuery[]>();
const menuProductsList = ref<DailyMenuProduct[]>();
const productCategoryList = ref<DailyMenuProductCategory[]>();
const shopList = ref<any[]>([]);

const dialog = reactive({
  title: "",
  visible: false,
  visibleProduct: false,
  visibleMenuProduct: false,
});

const originData = (): DailyMenuForm => ({
  id: undefined,
  type: 0,
  date: undefined,
  shop_id: undefined,
  start_time: undefined,
  end_time: undefined,
  menu_type: 0,
  is_can_order: 0,
  expire_date: undefined,
  order_start_time: undefined,
  order_end_time: undefined,
  deliver_time: undefined,
  status: 1,
  productIds: [],
});

const formData = reactive<DailyMenuForm>(originData());

const rules = reactive({
  title: [{required: true, message: "请输入名称", trigger: "blur"}],
  status: [{required: true, message: "请选择状态", trigger: "blur"}],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getDailyMenuList(queryParams)
    .then(({data}) => {
      lists.value = data.items || null;
      total.value = data.total;
      lastPage.value = data.lastPage || 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleProducts(id?: number) {
  if (!id) return;
  loading.value = true;

  getMenuProducts(id).then((data) => {
    menuProductsList.value = data.data || null;
    loading.value = false;
    dialog.visibleMenuProduct = true;
    dialog.title = "菜品详情";
  });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.stype = "";
  queryParams.pageNum = 1;
  handleQuery();
}

/** 打开表单弹窗 */
function openDialog(id?: number, type: number = 0) {
  formData.menu_type = type;
  modelFields.value = dailyMenuFields(type || 0) || {};
  if (current_role != "sys" && modelFields.value.shop_id) {
    // modelFields.value.shop_id.hidden = 1;
  }

  dialog.visible = true;
  getSupplierOptions({type: type})
    .then((data) => {
      if (modelFields.value && modelFields.value["shop_id"]) {
        modelFields.value["shop_id"]["options"] = data.data || [];
        if (current_role != "sys") {
          formData.shop_id = modelFields.value["shop_id"]["options"][0]!.id;
        }
      }
    })
    .then(() => {
      if (id) {
        dialog.title = "修改菜单";
        getDailyMenuDetail(id).then(({data}) => {
          Object.assign(formData, data);
        });
      } else {
        dialog.title = "新增菜单";
      }
    });
}

/** 打开选择菜品 */
function openSelectDialog(id: number) {
  if (!id) {
    ElMessage.warning("参数异常");
    return;
  }

  dialog.visibleProduct = true;
  getMenuProductsOptions(id).then((data) => {
    dialog.title = "选择菜品";
    productCategoryList.value = data.data.categoryList || [];
    Object.assign(formData, {id: id});
  });
}

/** 保存提交 */
function handleSubmit() {
  objFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.id;
      if (roleId) {
        updateDailyMenu(roleId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog(1);
            resetForm();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        createDailyMenu(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog(1);
            resetForm();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/**
 * 菜单选择保存
 */
function handleSelectSubmit() {
  if (!formData.id) {
    ElMessage.warning("参数错误");
    return;
  }

  loading.value = true;
  addDailyMenuProducts(formData.id, formData)
    .then((data) => {
      dialog.visibleProduct = false;
      ElMessage.success("添加成功");
      resetForm();
      // objFormRef.value.resetFields();
      handleQuery();
    })
    .finally(() => (loading.value = false));
}

/** 关闭表单弹窗 */
function closeDialog(type = 0) {
  dialog.visible = false;
  dialog.visibleMenuProduct = false;
  dialog.visibleProduct = false;

  if (type) resetForm();
}

/** 重置表单 */
function resetForm() {
  objFormRef.value.resetFields();
  objFormRef.value.clearValidate();
  Object.assign(formData, originData());
}

/** 删除 */
function handleDelete(id: number) {
  if (!id) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中记录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteDailyMenu(id)
      .then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

/** 删除 */
function handleMenuProductDelete(idx: number, pidx: number) {
  if (!menuProductsList.value || !menuProductsList.value[idx]) return;
  const product = menuProductsList.value[idx].products[pidx];
  if (!product) {
    ElMessage.warning("数据错误");
    return;
  }

  ElMessageBox.confirm("确认删除菜品`" + (product.title || "") + "`?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteProduct(product.id)
      .then(() => {
        if (menuProductsList.value) {
          menuProductsList.value[idx].products.splice(pidx, 1);
          if (
            !menuProductsList.value[idx].products ||
            menuProductsList.value[idx].products.length == 0
          ) {
            menuProductsList.value.splice(idx, 1);
          }
        }
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

/**
 * 复制记录
 * @param id
 */
function copyRow(id: number) {
  if (!id) {
    ElMessage.warning("数据错误");
    return;
  }
  ElMessageBox.confirm("确认复制菜单?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    copyDailyMenu(id)
      .then((data) => {
        ElMessage.success("复制成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

/**
 * 选择所有
 * @param idx
 */
function handleCheckAllChange(idx: number) {
  if (productCategoryList?.value) {
    const productCategory = productCategoryList?.value[idx];
    if (productCategory.checkAll) {
      productCategory.products.forEach((item: any) => {
        const productIds = formData.productIds || [];
        productIds.push(productCategory.id + "-" + item.id);
        formData.productIds = productIds || [];
      });
    } else {
      productCategory!.products.forEach((item: any) => {
        const productIds = formData.productIds || [];
        for (const k in productIds) {
          if (productIds[k] == productCategory.id + "-" + item.id) {
            productIds.splice(Number(k), 1);
            break;
          }
        }
        formData.productIds = productIds || [];
      });
    }
  }
}

let dragIndex = 0;

function dragStart(event: any, index: number, pk: number) {
  event.stopPropagation();
  dragIndex = pk;
  event.target.classList.add("moveing");
}

function dragEnter(event: any, index: number, pk: number) {
  event.preventDefault();

  if (dragIndex != pk) {
    // if (menuProductsList.value[index] != "undefined") {
    const source = (menuProductsList as any).value[index].products[dragIndex];

    (menuProductsList as any).value[index].products.splice(dragIndex, 1);
    (menuProductsList as any).value[index].products.splice(pk, 0, source);

    let productIds: number[] = [];
    (menuProductsList as any).value[index].products.forEach((e1: any) => {
      productIds.push(e1.id);
    });

    sortDailyMenu(
      (menuProductsList as any).value[index]?.menu_id,
      productIds
    ).then((res: any) => {
      console.log(res);
    });
    // }

    dragIndex = pk;
  }
}

function dragOver(event: any) {
  event.preventDefault();
  event.dataTransfer.dropEffect = "move";
}

function dragEnd(event: any) {
  event.target.classList.remove("moveing");
}

onMounted(() => {
  handleQuery();
  getSupplierOptions().then((data) => {
    shopList.value = data.data;
  });
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form
        class="pull-left"
        ref="queryFormRef"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item style="width: 140px;">
          <el-select
            clearable
            v-model="queryParams.stype"
            prop="stype"
            placeholder="请选择类型"
          >
            <el-option
              :key="Number(ok)"
              :label="op"
              v-for="(op, ok) in typeOptions"
              :value="Number(ok)"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label=""
          prop=""
          style="width: 160px"
          v-if="current_role == 'sys'"
        >
          <el-select v-model="queryParams.shop_id" placeholder="请选择店铺">
            <el-option :label="op.title" v-for="op in shopList" :value="Number(op.id)"/>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search/>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh/>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="pull-right">
        <el-button
          v-hasPerm="['shop:daily-menu:edit']"
          type="danger"
          @click="openDialog(0, 0)"
          v-if="current_role == 'sys' || useStore.user!.shop_type == 0"
        >
          <i-ep-plus/>
          新增单店菜单
        </el-button>
        <el-button
          v-hasPerm="['shop:daily-menu:edit']"
          type="primary"
          @click="openDialog(0, 1)"
          v-if="current_role == 'sys' || useStore.user!.shop_type == 1"
        >
          <i-ep-plus/>
          新增食堂菜单
        </el-button>
      </div>
      <div class="clear"></div>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="lists"
        highlight-current-row
      >
        <el-table-column label="编号" prop="id" min-width="100"/>
        <el-table-column label="菜单类型" prop="menu_type" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.menu_type == 1 ? 'primary' : 'info'">
              {{ scope.row.menu_type == 1 ? "食堂" : "普通" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="菜单餐段" prop="type" min-width="100">
          <template #default="scope">
            {{
              scope.row.menu_type == 1 ? typeOptions[scope.row.type] : "全天"
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="所属餐厅"
          prop="supplier_title"
          min-width="100"
        />
        <el-table-column label="菜单时间" min-width="100">
          <template #default="scope">
            <span v-if="scope.row.menu_type == 1">{{ scope.row.date }}</span>
            <template v-else>
              <div>起：{{ scope.row.expire_start_date }}</div>
              <div>止：{{ scope.row.expire_end_date }}</div>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="菜品" prop="products">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleProducts(scope.row.id)"
            >查看菜品（{{ scope.row.product_amount || 0 }}）
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="订餐时间" min-width="140">
          <template #default="scope">
            <template v-if="scope.row.menu_type == 1">
              <div style="font-size: 13px">
                起：{{
                  scope.row.menu_type == 1
                    ? scope.row.start_time
                    : scope.row.order_start_time
                }}
              </div>
              <div style="font-size: 13px">
                止：{{
                  scope.row.menu_type == 1
                    ? scope.row.end_time
                    : scope.row.order_end_time
                }}
              </div>
            </template>

            <template v-else>
              <div style="font-size: 13px">
                起：{{ scope.row.store_time[0] || "" }}
              </div>
              <div style="font-size: 13px">
                止：{{ scope.row.store_time[1] || "" }}
              </div>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="送达时间" prop="deliver_time">
          <template #default="scope">
            {{ scope.row.menu_type == 1 ? scope.row.deliver_time : "即点即送" }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="160">
          <template #default="scope">
            <el-tag :type="statusOptions[scope.row.status].type"
            >{{ statusOptions[scope.row.status].title }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="140">
          <template #default="scope">
            <el-button
              v-hasPerm="['shop:daily-menu:selectProduct']"
              type="primary"
              size="small"
              link
              @click="openSelectDialog(scope.row.id)"
            >
              <i-ep-search class="margin3-r"/>
              选择菜品
            </el-button>

            <el-button
              v-hasPerm="['shop:daily-menu:copy']"
              type="primary"
              size="small"
              link
              @click="copyRow(scope.row.id)"
            >
              <i-ep-DocumentCopy class="margin3-r"/>
              复制
            </el-button>

            <el-button
              v-hasPerm="['shop:daily-menu:edit']"
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row.id, scope.row.menu_type)"
            >
              <i-ep-edit class="margin3-r"/>
              编辑
            </el-button>

            <el-button
              v-hasPerm="['shop:daily-menu:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete class="margin3-r"/>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:lastPage="lastPage"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 编辑表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="540px"
      v-loading="loading"
      @close="closeDialog(1)"
    >
      <el-form
        ref="objFormRef"
        :model="formData"
        :rules="rules"
        label-width="160px"
      >
        <el-form-item
          :label="field.title"
          :prop="fk.toString()"
          v-for="(field, fk) in modelFields"
          :key="fk"
          :class="field.hide ? 'el-hide' : ''"
        >
          <el-radio-group v-model="formData[fk]" v-if="field.type == 'radio'">
            <el-radio
              :label="Number(ok)"
              v-for="(op, ok) in field.options"
              :key="ok"
            >{{ field.rangeKey ? op.title : op }}
            </el-radio>
          </el-radio-group>

          <el-date-picker
            v-model="formData[fk]"
            :type="field.type"
            placeholder="请选择"
            :value-format="field.format"
            v-else-if="
              field.type == 'date' ||
              field.type == 'datetime' ||
              field.type == 'daterange'
            "
          />
          <el-time-picker
            v-model="formData[fk]"
            :type="field.type"
            placeholder="请选择"
            :value-format="field.format"
            v-else-if="field.type == 'time'"
          />
          <el-select v-model="formData[fk]" v-else-if="field.type == 'select'">
            <el-option
              :key="Number(ok)"
              :label="op"
              v-for="(op, ok) in field.options"
              :value="Number(ok)"
              v-if="field.isValue"
            />
            <el-option
              :key="Number(op.id)"
              :label="op.title"
              v-for="op in field.options"
              :value="Number(op.id)"
              v-else
            />
          </el-select>

          <el-input
            :type="field.type || 'text'"
            v-model="formData[fk]"
            :placeholder="'请输入' + field.title"
            v-else
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog(1)" type="default">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择菜品 -->
    <el-dialog
      v-model="dialog.visibleProduct"
      :title="dialog.title"
      width="1000"
      v-loading="loading"
      @close="closeDialog()"
      class="mp-dialog mps-dialog"
    >
      <template #header>
        <strong>{{ dialog.title }}</strong>
      </template>
      <el-form ref="objFormRef" :model="formData" label-width="140px">
        <div
          class="m-4"
          v-for="(row, index) in productCategoryList"
          :key="'mp' + index"
        >
          <template v-if="row.products.length > 0">
            <div class="block-title">
              <strong>{{ row.title }} </strong>
              <el-checkbox
                style="padding: 15px 10px 0px; position: relative; top: 3px"
                v-model="row.checkAll"
                @change="handleCheckAllChange(index)"
              >全选
              </el-checkbox>
            </div>
            <div class="ul margin10-b" v-if="row.products.length > 0">
              <template v-for="(prow, pk) in row.products" :key="'pp' + pk">
                <el-checkbox-group class="li" v-model="formData['productIds']">
                  <el-checkbox
                    :label="prow.title"
                    :value="row.id + '-' + prow.id"
                    :key="prow.id"
                  />
                </el-checkbox-group>
              </template>
            </div>
            <div v-else>
              <el-text type="info">暂无商品</el-text>
            </div>
          </template>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSelectSubmit"
          >确 定
          </el-button>
          <el-button @click="closeDialog()" type="default">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 产品详情-->
    <el-dialog
      v-model="dialog.visibleMenuProduct"
      :title="dialog.title"
      v-loading="loading"
      @close="closeDialog()"
      width="800"
      class="mp-dialog fixed-header-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <span>{{ dialog.title }}</span>
        </div>
      </template>
      <div
        class="m-4"
        v-for="(row, index) in menuProductsList"
        :key="'mp' + index"
      >
        <div class="block-title">
          <strong>{{ row.title }}</strong>
        </div>
        <div class="mp-ul">
          <template v-for="(prow, pk) in row.products" :key="'pp' + pk">
            <div
              type="danger"
              @click="handleMenuProductDelete(index, pk)"
              class="mp-li"
              draggable="true"
              @dragstart="dragStart($event, index, pk)"
              @dragenter="dragEnter($event, index, pk)"
              @dragover="dragOver"
              @dragend="dragEnd"
              v-if="prow"
            >
              <img :src="defaultSettings.imgDomain + prow.thumb" class="pimg"/>
              <span>{{ prow.title }}</span>
              <i-ep-delete class="del"/>
            </div>
          </template>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.el-select,
.el-date-editor {
  --el-select-width: 280px !important;
}

.el-date-editor {
  --el-date-editor-width: 280px !important;
  //width: 400px !important;
}

:deep(.el-date-editor.el-input),
:deep(.el-date-editor.el-input__wrapper) {
  width: 280px !important;
}

.el-popper {
  z-index: 1001 !important; /* 确保高于其他元素 */
}

:deep(.mp-dialog) {
  padding-bottom: 30px !important;
}

.mp-dialog .m-4 {
  margin-bottom: 0px !important;
  margin-top: 10px;
}

.mp-dialog .block-title {
  background: #f8f8f8;
  line-height: 40px;
  padding: 0px 15px;
  font-weight: bolder;
  margin-bottom: 10px;
}

.mp-dialog .mp-ul .pimg {
  height: 30px;
  width: 30px;
  vertical-align: middle;
  margin-right: 5px;
  background: transparent;
  position: relative;
  top: -2px;
}

.mp-dialog .mp-ul .mp-li {
  padding: 0px 30px 0 10px;
  display: inline-block;
  font-size: 13px;
  margin-right: 10px;
  width: 160px;
  border: 1px solid #eee;
  margin-bottom: 5px;
  border-radius: 2px;
  overflow: hidden;
  height: 40px;
  line-height: 40px;
  position: relative;
}

.mp-dialog .mp-ul .mp-li:hover {
  background: #f8f8f8;
  cursor: pointer;
}

:deep(.mp-dialog) .el-dialog__body {
  max-height: 540px !important;
  overflow-y: auto;
}

:deep(.mp-dialog) .el-dialog__body .del {
  position: absolute;
  top: 11px !important;
  right: 10px !important;
  color: red;
}

:deep(.mps-dialog) {
  padding-bottom: 0px !important;

  .ul {
    margin-bottom: 30px !important;
  }
}

:deep(.mps-dialog) .ul .li {
  display: inline-block;
  padding-right: 10px;
}

:deep(.mps-dialog) .el-dialog__body {
  margin-bottom: 15px;
}

:deep(.mps-dialog) .ul .el-checkbox-group {
  padding: 0px 5px;
  min-width: 134px;
}
</style>
